package com.leyou.item.web;

import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("spec")
public class SpecController {

    private SpecGroupService groupService;
    private SpecParamService paramService;

    public SpecController(SpecGroupService groupService, SpecParamService paramService) {
        this.groupService = groupService;
        this.paramService = paramService;
    }

    //根据分类查询规格组
    @GetMapping("/groups/of/category")
    public ResponseEntity<List<SpecGroupDTO>> queryGroupByCategory(
            @RequestParam("id") Long id){
        return ResponseEntity.ok(
                SpecGroupDTO.convertEntityList(
                        groupService.query().eq("category_id", id).list()
                )
        );
    }

    //查询规格参数集合
    @GetMapping("/params")
    public ResponseEntity<List<SpecParamDTO>> querySpecParams(
            @RequestParam(value = "categoryId", required = false) Long categoryId,
            @RequestParam(value = "groupId", required = false) Long groupId,
            @RequestParam(value = "searching", required = false) Boolean searching
    ){
        return ResponseEntity.ok(paramService.querySpecParams(categoryId, groupId, searching));
    }

    //新增检查组
    @PostMapping("/group")
    public ResponseEntity<Void> saveGroup(@RequestBody SpecGroupDTO groupDTO){
        groupService.save(groupDTO.toEntity(SpecGroup.class));
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    //修改规格组
    @PutMapping("/group")
    public ResponseEntity<Void> updateGroup(
            @RequestBody SpecGroupDTO groupDTO){
        groupService.updateById(groupDTO.toEntity(SpecGroup.class));
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    //查询规格组及规格参数
    @GetMapping("/list")
    public ResponseEntity<List<SpecGroupDTO>> querySpecList(@RequestParam("id") Long categoryId) {
        return ResponseEntity.ok(groupService.querySpecList(categoryId));
    }

    //新增规格参数
    //@RequestBody,前台传过来的数据用这个接收一下
    @PostMapping("/param")
    public ResponseEntity<Void> addSpecParam(@RequestBody SpecParamDTO paramDTO){
        groupService.insertSpecParam(paramDTO);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @PutMapping("/param")
    public  ResponseEntity<Void> updateSpecParam(@RequestBody SpecParamDTO paramDTO){
        paramService.updateById(paramDTO.toEntity(SpecParam.class));
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }


}